﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Truron.Purchase.Interface;
using Truron.Purchase.Api.Utility;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Truron.Purchase.Model;
using Newtonsoft.Json;
using Truron.Purchase.Utility;
using Truron.Purchase.Service;

namespace Truron.Purchase.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class PurchaseOuterNoteController : ControllerBase
    {
        private readonly IPurchase_OuterNoteService _purchase_OuterNoteService;
        private readonly IPurchase_OuterNoteApprovalService _purchase_OuterNoteApprovalService;
        private readonly IPurchase_OuterRequestNoteRelationService _purchase_OuterRequestNoteRelationService;
        private readonly IPurchase_SupplyService _purchase_SupplyService;
        private readonly IPurchase_OuterNoteDetailService _Purchase_OuterNoteDetailService;
        private readonly IPurchase_OuterNotePayRelationService _Purchase_OuterNotePayRelationService;
        private readonly IPurchase_OuterNoteInvoiceRelationService _Purchase_OuterNoteInvoiceRelationService;
        public PurchaseOuterNoteController(IPurchase_OuterNoteService Purchase_OuterNoteService, IPurchase_OuterNoteApprovalService Purchase_OuterNoteApprovalService,
            IPurchase_OuterRequestNoteRelationService Purchase_OuterRequestNoteRelationService, IPurchase_SupplyService Purchase_SupplyService, 
            IPurchase_OuterNoteDetailService Purchase_OuterNoteDetailService, IPurchase_OuterNotePayRelationService Purchase_OuterNotePayRelationService,
            IPurchase_OuterNoteInvoiceRelationService Purchase_OuterNoteInvoiceRelationService)
        {
            _purchase_OuterNoteService = Purchase_OuterNoteService;
            _purchase_OuterNoteApprovalService = Purchase_OuterNoteApprovalService;
            _purchase_OuterRequestNoteRelationService = Purchase_OuterRequestNoteRelationService;
            _purchase_SupplyService = Purchase_SupplyService;
            _Purchase_OuterNoteDetailService = Purchase_OuterNoteDetailService;
            _Purchase_OuterNotePayRelationService = Purchase_OuterNotePayRelationService;
            _Purchase_OuterNoteInvoiceRelationService = Purchase_OuterNoteInvoiceRelationService;
        }
        [HttpPost]
        public IActionResult GetNoteList(LayPageModel param)
        {

            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAll(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            int OuterStatus = -1;

            List<int> ownerIds = new List<int>();
            var queryParam = param.searchJson.ToJObject();
            if (queryParam["ownerIds"].IsEmpty())
            {
                ownerIds = userDict.Where(x => x.Value.isSub).Select(x => x.Key).ToList();
            }
            else
            {
                if (queryParam["ownerIds"].ToString().IndexOf('-') >= 0)
                {
                    ownerIds.Add(Convert.ToInt32(queryParam["ownerIds"][0].ToString().Split('-')[0]));
                    OuterStatus = Convert.ToInt32(queryParam["ownerIds"][0].ToString().Split('-')[1]);
                }
                else
                {
                    ownerIds.Add(Convert.ToInt32(queryParam["ownerIds"][0].ToString()));
                }

            }
            if (ownerIds.Count == 0)
            {
                ownerIds.Add(userToken.UserId);
            }
            if (!queryParam["deptId"].IsEmpty())
            {
                var userIdTuple = SysCenterServiceHelp.Instance.GetUserByDept(userToken, (int)queryParam["deptId"]);
                if (userIdTuple.code > 0)
                    return Ok(JsonConvert.SerializeObject(new ResultData<object>(userIdTuple.code)));
                ownerIds = userIdTuple.ids.ToList();
            }

            int pageSize = param.limit, pageIndex = param.page;
            var noteTuple = _purchase_OuterNoteService.GetNoteList(param.searchKey, pageSize, pageIndex,param.searchJson,OuterStatus,ownerIds);
            var approvelist = _purchase_OuterNoteApprovalService.GetApproveListByIds(noteTuple.list.Select(x => x.Id).ToList());
            foreach (var note in noteTuple.list)
            {
                //if (note.FlowStatus == (int)OuterNoteStatus.purchaseManagerAudit)
                //{
                //    note.AuditerId = 279;
                //    note.AuditerName = "王接龙";
                //}
                //else if (note.FlowStatus == (int)OuterNoteStatus.waitSubmit)
                //{
                //    note.AuditerId = note.OwnerId;
                //    note.AuditerName = userDict.ContainsKey(note.OwnerId) ? userDict[note.OwnerId].RealName : "用户不存在";
                //    //entity.OwnerName = entity.OwnerId == 0 ? "等待分配" : (userDict.ContainsKey(entity.OwnerId) ? userDict[entity.OwnerId].RealName : "用户不存在");

                //}
                //else if (note.FlowStatus == (int)OuterNoteStatus.managerAudit)
                //{
                //    note.AuditerId = 2;
                //    note.AuditerName = "陈洪道";
                //}
                if(note.FlowStatus==0)
                {
                    note.AuditerId = approvelist.Find(x => x.NoteId == note.Id)==null?0: approvelist.Find(x => x.NoteId == note.Id).Approver;
                    note.AuditerName = approvelist.Find(x => x.NoteId == note.Id) == null ? "" : approvelist.Find(x => x.NoteId == note.Id).ApproverName;

                }
                else if (note.FlowStatus == (int)OuterNoteStatus.finish)
                {
                    note.AuditerId = 0;
                    note.AuditerName = "";
                }
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = noteTuple.list, count = noteTuple.count }));
            //return null;
        }
        public class AcceptParam
        {
            public int Id { get; set; }

            public int limit { get; set; }
            public int page { get; set; }
            public Purchase_OuterNote ent { get; set; }
            public int[] ids { get; set; }
            public int ownerId { get; set; }


            #region 搜索参数
            //public ClueStatus? clueStatus { get; set; }
            public string searchKey { get; set; }//搜索key
            public int deptId { get; set; }
            public int[] ownerIds { get; set; }
            public bool? filedStatus { get; set; }
            public DateTime? beginTime { get; set; }
            public DateTime? endTime { get; set; }
            #endregion
        }
        [HttpPost]
        public IActionResult GetNoteDetail(Purchase_OuterNote param)
        {
            if (param.Id <= 0)
                return Ok(JsonConvert.SerializeObject(new ResultData(ErrorCodeConst.ParameterError)));
            var ent = _purchase_OuterNoteService.GetPurchase_OuterNoteDetail(param.Id);
            var approvelist = _purchase_OuterNoteApprovalService.GetApproveListByIds(new List<int>() { ent.Id});
            if (ent == null)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = null }));

            if (ent.FlowStatus == 0)
            {
                ent.AuditerId = approvelist.Find(x => x.NoteId == ent.Id) == null ? 0 : approvelist.Find(x => x.NoteId == ent.Id).Approver;
                ent.AuditerName = approvelist.Find(x => x.NoteId == ent.Id) == null ? "" : approvelist.Find(x => x.NoteId == ent.Id).ApproverName;

            }
            else if (ent.FlowStatus == (int)OuterNoteStatus.finish)
            {
                ent.AuditerId = 0;
                ent.AuditerName = "";
            }
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);


            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = ent,code=0 }));
        }
        /// <summary>
        /// 添加线索信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SaveNote(RecParam param)
        {
            Purchase_OuterNote entity = JsonConvert.DeserializeObject< Purchase_OuterNote >(param.strEntity) ;
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            bool createFlow = false;
            if (entity.Id == 0)
            {
                createFlow = true;
            }
            var resultCode = _purchase_OuterNoteService.SaveNote(userToken.UserId, entity);
            if(createFlow)
            {
                Purchase_OuterNoteApproval approve = new Purchase_OuterNoteApproval();
                //approve.Create(userToken);
                approve.IsFinish = 0;
                approve.StepNo = 0;
                approve.NoteId = resultCode.NoteId;
                approve.Approver = userToken.UserId;
                approve.ApproverName = userToken.RealName;
                _purchase_OuterNoteApprovalService.Save(approve, userToken);
            }
            if(param.strDetail.Length>0)
            {
                List<Purchase_OuterNoteDetail> detaillist= param.strDetail.ToObject<List<Purchase_OuterNoteDetail>>();
                foreach(var d in detaillist)
                {
                    if(d.Id==0)
                    {
                        d.Create(userToken);
                        d.NoteId = resultCode.NoteId;
                        
                    }
                    _Purchase_OuterNoteDetailService.Save(d, userToken);
                }
            }
            //添加功能，保存的时候调整预提成本
            //decimal singlePrice=entity.PretaxAmount/entity.TypeNum
            var relationlist = _purchase_OuterRequestNoteRelationService.GetListByNoteId(resultCode.NoteId);
            for(int i=0;i<relationlist.Count;i++)
            {
                relationlist[i].ExpectMoney = Math.Round(entity.PretaxAmount / entity.TypeNum * relationlist[i].OuterNum,2);
                _purchase_OuterRequestNoteRelationService.Save(relationlist[i], userToken);
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code=0,data=new { NoteId=resultCode.NoteId,SinglePrice=resultCode.SinglePrice} }));
        }
        public class RecParam
        {
            public string strEntity { get; set; }
            public string strDetail { get; set; }
        }
        public IActionResult SaveApprove(Purchase_OuterNoteApproval entity)
        {
            //Purchase_OuterRequestApproval entity = param.strEntity.ToObject<Purchase_OuterRequestApproval>();
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var SendUser = _purchase_OuterNoteApprovalService.FinishNode(entity, userToken);

            var nextOnt = _purchase_OuterNoteService.ApproveNote(entity, userToken, SendUser.Approver,SendUser.ApproverName,SendUser.step);
            if(nextOnt!=null)
            {
                _purchase_OuterNoteApprovalService.Save(nextOnt, userToken);
            }
            

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = nextOnt }));
        }
        public class GetApproveListParam
        {
            public int NoteId { get; set; }
        }
        public IActionResult GetApproveList(GetApproveListParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var list = _purchase_OuterNoteApprovalService.GetApproveList(param.NoteId);
            var userTuple = SysCenterServiceHelp.Instance.GetUserAll(userToken);//获取所有用户信息
            foreach(var entity in list)
            {
                entity.UserName = userTuple.list.Find(x => x.UserID == entity.Approver).RealName;
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }
        public class GetRelationNoteListParam
        {
            public int RequestId { get; set; }
        }
        public IActionResult GetRelationNoteList(GetRelationNoteListParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var resultList = _purchase_OuterRequestNoteRelationService.GetRelationListByRequestIds(new List<int>() { param.RequestId }).ToList();
            List<int> NoteDIds = resultList.Select(x=>x.OuterNoteId).Distinct().ToList();
            var supplyList = _purchase_SupplyService.GetAllList();
            List<Purchase_OuterNoteDetail> detailList = _Purchase_OuterNoteDetailService.GetListByIds(NoteDIds);
            List<Purchase_OuterNote> mlist = _purchase_OuterNoteService.GetRelationList(detailList.Select(x=>x.NoteId).Distinct().ToList());
          

            var relationList = _purchase_OuterRequestNoteRelationService.GetRelationListByNoteIds(detailList.Select(x => x.Id).Distinct().ToList()).ToList();
            //foreach (var entity in list)
            //{
            //    entity.SupplyName = supplyList.Find(x => x.Id == entity.SuppliesId).Supplier;
            //    entity.UserNum = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum);
                
            //    entity.thisNum= relationList.FindAll(x => x.OuterNoteId == entity.Id && x.OuterRequestId == param.RequestId).Sum(x => x.OuterNum);
            //    //ResetNum改为除本外本单关联的数量
            //    entity.ResetNum = entity.TypeNum - entity.UserNum + entity.thisNum;
            //}
            foreach(var entity in detailList)
            {
                entity.SupplyName = supplyList.Find(x => x.Id == mlist.Find(x => x.Id == entity.NoteId).SuppliesId).Supplier;
                entity.Code = mlist.Find(x => x.Id == entity.NoteId).Code;
                entity.RelationNum = relationList.Find(x => x.OuterNoteId == entity.Id && x.OuterRequestId == param.RequestId).OuterNum;
                //entity.UseNum = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum);
                //entity.ResetNum = entity.TypeNum - entity.UseNum;
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = detailList }));
        }
        public IActionResult GetPreRelationNoteList()
        {
            var resultList = new List<Purchase_OuterNote>();
            var list = _purchase_OuterNoteService.GetPreRelationNoteList();
            var supplyList = _purchase_SupplyService.GetAllList();
            var relationList = _purchase_OuterRequestNoteRelationService.GetRelationListByNoteIds(list.Select(x => x.Id).Distinct().ToList()).ToList();
            foreach(var entity in list)
            {
                if(entity.TypeNum> relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum))
                {
                    entity.SupplyName = supplyList.Find(x => x.Id == entity.SuppliesId).Supplier;
                    entity.UserNum = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum);
                    entity.ResetNum = entity.TypeNum - entity.UserNum;
                    resultList.Add(entity);
                }
                //entity.SupplyName = supplyList.Find(x => x.Id == entity.SuppliesId).Supplier;
                //entity.UserNum = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum);
                //entity.ResetNum = entity.TypeNum - entity.UserNum;

            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = resultList }));
        }
        public class GetPreRelationDetailListParam
        {
            public string searchKey { get; set; }
        }
        public IActionResult GetPreRelationDetailList(GetPreRelationDetailListParam param)
        {
            var resultList = new List<Purchase_OuterNoteDetail>();
            var mlist = _purchase_OuterNoteService.GetPreRelationNoteList();
            var dlist = _Purchase_OuterNoteDetailService.GetListByNoteIds(mlist.Select(x => x.Id).ToList());
            var relationList = _purchase_OuterRequestNoteRelationService.GetRelationListByNoteIds(dlist.Select(x => x.Id).Distinct().ToList()).ToList();
            var supplyList = _purchase_SupplyService.GetAllList();
            foreach (var entity in dlist)
            {
                if (entity.TypeNum > relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum))
                {
                    entity.SupplyName = supplyList.Find(x => x.Id == mlist.Find(x=>x.Id==entity.NoteId).SuppliesId).Supplier;
                    entity.Code = mlist.Find(x => x.Id == entity.NoteId).Code;
                    entity.UseNum = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.OuterNum);
                    entity.ResetNum = entity.TypeNum - entity.UseNum;
                    resultList.Add(entity);
                }
            }
            if(!string.IsNullOrEmpty(param.searchKey))
            {
                resultList = resultList.FindAll(x => (param.searchKey.Contains(x.Code) || param.searchKey.Contains(x.SupplyName) || param.searchKey.Contains(x.Item) || param.searchKey.Contains(x.ItemType)));
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = resultList }));
        }
        public class FinishOuterNoteParam
        {
            public int NoteId { get; set; }
            //public decimal RealMoney { get; set; }
        }
        public IActionResult FinishOuterNote(FinishOuterNoteParam param)
        {
            if(param.NoteId==0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(998)));
            }
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            //获取所有关联的付款单
            List<Purchase_OuterNotePayRelation> PayList = _Purchase_OuterNotePayRelationService.GetListByOuterNoteIds(new List<int>() { param.NoteId });
            decimal realMoney = PayList.Sum(x => x.MatchMoney);
            decimal SingleMoney = _purchase_OuterNoteService.FinishOuterNote(param.NoteId, realMoney, userToken);
            _purchase_OuterRequestNoteRelationService.UpdateRealMoney(param.NoteId, realMoney, userToken, SingleMoney);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code=0}));
        }
        public IActionResult GetOuterNoteTreeData(GetTreeDataParam param)
        {
            //先获取所有用户
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));
            var userlist=userTuple.list.FindAll(x => x.isSub);
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            //获取所有业务数据
            List<Purchase_OuterNote> NoteList = _purchase_OuterNoteService.GetAllList();
            //for(int i=0;i<param.OrderList.Count;i++)
            //{
            //    if()
            //}
            List<TreeModel> ResultTree = new List<TreeModel>();
            bool first = true;
            if (param.OrderList[0] == "user")
            {

                //用户、状态分组
                foreach (var entity in userlist)
                {
                    if (NoteList.Exists(x => x.OwnerId == entity.UserID))
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"{entity.EnglishName}({entity.RealName}) {NoteList.Count(x => x.OwnerId == entity.UserID)}";
                        temp.id = entity.UserID.ToString();
                        temp.field = "user";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        //012,3,4三种状态
                        int status1Count = NoteList.Count(x => x.OwnerId == entity.UserID && (x.FlowStatus == (int)OuterNoteStatus.waitSubmit|| x.FlowStatus == (int)OuterNoteStatus.purchaseManagerAudit || x.FlowStatus == (int)OuterNoteStatus.managerAudit));
                        if (status1Count > 0)
                        {
                            TreeModel status1 = new TreeModel();
                            status1.title = $"审批中({status1Count.ToString()})";
                            status1.id = entity.UserID.ToString() + "-0";
                            status1.field = "userstatus";
                            status1.href = "";
                            temp.children.Add(status1);
                        }

                        int status2Count = NoteList.Count(x => x.OwnerId == entity.UserID && x.FlowStatus == (int)OuterNoteStatus.finish);
                        if (status2Count > 0)
                        {
                            TreeModel status2 = new TreeModel();
                            status2.title = $"审批通过({status2Count.ToString()})";
                            status2.id = entity.UserID.ToString() + "-3";
                            status2.field = "userstatus";
                            status2.href = "";
                            temp.children.Add(status2);
                        }

                        int status3Count = NoteList.Count(x => x.OwnerId == entity.UserID && x.FlowStatus == (int)OuterNoteStatus.close);
                        if (status3Count > 0)
                        {
                            TreeModel status3 = new TreeModel();
                            status3.title = $"关闭({status3Count.ToString()})";
                            status3.id = entity.UserID.ToString() + "-4";
                            status3.field = "userstatus";
                            status3.href = "";
                            temp.children.Add(status3);
                        }
                        ResultTree.Add(temp);
                    }
                }
            }
            else
            {
                //状态、用户分组
                var stutsList = NoteList.Select(x => x.FlowStatus).OrderBy(x=>x).Distinct().ToList();
                foreach (int i in stutsList)
                {
                    if (i == 0|| i == 1|| i == 2)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"审批中({NoteList.Count(x => (x.FlowStatus == 0|| x.FlowStatus == 1|| x.FlowStatus == 2))})";
                        temp.id = "0";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userlist)
                        {
                            if (NoteList.Exists(x => x.OwnerId == entity.UserID && x.FlowStatus == 0))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.OwnerId == entity.UserID && (x.FlowStatus == 0 || x.FlowStatus == 1 || x.FlowStatus == 2))})";
                                userTree.id = "0-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }


                        }

                        ResultTree.Add(temp);
                    }
                    else if (i == 3)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"审批通过({NoteList.Count(x => x.FlowStatus == 3)})";
                        temp.id = "3";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userlist)
                        {
                            if (NoteList.Exists(x => x.OwnerId == entity.UserID && x.FlowStatus == 1))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.OwnerId == entity.UserID && x.FlowStatus == 3)})";
                                userTree.id = "3-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                        }
                        ResultTree.Add(temp);
                    }
                    else if (i == 4)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"关闭({NoteList.Count(x => x.FlowStatus == 4)})";
                        temp.id = "4";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userlist)
                        {
                            if (NoteList.Exists(x => x.OwnerId == entity.UserID && x.FlowStatus == 4))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.OwnerId == entity.UserID && x.FlowStatus == 4)})";
                                userTree.id = "4-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                        }
                        ResultTree.Add(temp);
                    }
                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = ResultTree }));
        }
        public IActionResult GetOuterNoteTreeDataNew(GetTreeDataParam param)
        {
            List<StatusModel> StatusList = new List<StatusModel>() {
                new StatusModel() { Code = 0, Name = "审批中" },
                new StatusModel() { Code = 3, Name = "开票&付款" },
                new StatusModel() { Code = 4, Name = "已关闭" }
            };
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));

            var userlist = userTuple.list.FindAll(x => x.isSub);
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            List<Purchase_OuterNote> NoteList = _purchase_OuterNoteService.GetAllList();
            NoteList = NoteList.FindAll(x=>userlist.Select(x=>x.UserID).Contains(x.OwnerId));
            List<TreeModel> ResultTree = new List<TreeModel>();

            if (param.OrderList.Count >= 1)
            {
                if (param.OrderList[0] == "user")
                {
                    foreach (var entity in userlist)
                    {
                        if (NoteList.Exists(x => x.OwnerId == entity.UserID))
                        {
                            TreeModel temp = new TreeModel();
                            temp.title = $"{entity.EnglishName}({entity.RealName})<font color='red'> {NoteList.Count(x => x.OwnerId == entity.UserID)}</font>";
                            temp.id = entity.UserID.ToString();
                            temp.field = "user";
                            temp.href = "";
                            temp.spread = true;
                            temp.disabled = false;
                            temp.children = new List<TreeModel>();



                            ResultTree.Add(temp);
                        }
                    }
                }
                else if (param.OrderList[0] == "status")
                {
                    foreach (var status in StatusList)
                    {
                        if (NoteList.Exists(x => x.FlowStatus == status.Code))
                        {
                            TreeModel temp = new TreeModel();
                            temp.title = $"{status.Name} <font color='red'>{NoteList.Count(x => x.FlowStatus == status.Code)}</font>";
                            temp.id = status.Code.ToString();
                            temp.field = "status";
                            temp.href = "";
                            temp.spread = true;
                            temp.disabled = false;
                            temp.children = new List<TreeModel>();



                            ResultTree.Add(temp);
                        }
                    }
                }
            }
            if (param.OrderList.Count >= 2)
            {
                if (param.OrderList[1] == "status")
                {
                    foreach (var entity in ResultTree)
                    {
                        foreach (StatusModel status in StatusList)
                        {
                            if (NoteList.Exists(x => x.OwnerId == Convert.ToInt32(entity.id) && x.FlowStatus == status.Code))
                            {
                                TreeModel temp = new TreeModel();
                                temp.title = $"{status.Name}<font color='red'> {NoteList.Count(x => x.OwnerId == Convert.ToInt32(entity.id) && x.FlowStatus == status.Code)}</font>";
                                temp.id = entity.id + "-" + status.Code.ToString();
                                temp.field = "userstatus";
                                temp.href = "";
                                temp.spread = true;
                                temp.disabled = false;
                                temp.children = new List<TreeModel>();
                                entity.children.Add(temp);
                            }
                        }
                    }
                }
                else if (param.OrderList[1] == "user")
                {
                    foreach (var entity in ResultTree)
                    {
                        foreach (var user in userlist)
                        {
                            if (NoteList.Exists(x => x.OwnerId == user.UserID && x.FlowStatus == Convert.ToInt32(entity.id)))
                            {
                                TreeModel temp = new TreeModel();
                                temp.title = $"{user.EnglishName}({user.RealName})<font color='red'> {NoteList.Count(x => x.OwnerId == user.UserID && x.FlowStatus == Convert.ToInt32(entity.id))}</font>";
                                temp.id = entity.id + "-" + user.UserID.ToString();
                                temp.field = "statususer";
                                temp.href = "";
                                temp.spread = true;
                                temp.disabled = false;
                                temp.children = new List<TreeModel>();
                                entity.children.Add(temp);
                            }
                        }
                    }
                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = ResultTree }));
        }
        public class GetOuterNoteDetailListParam
        {
            public int NoteId { get; set; }
        }
        public IActionResult GetOuterNoteDetailList(GetOuterNoteDetailListParam param)
        {
            var list = _Purchase_OuterNoteDetailService.GetListByNoteId(param.NoteId);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }
        public class DeleteDetailParam
        {
            public List<int> DelIds { get; set; }
        }
        public IActionResult DeleteDetail(DeleteDetailParam param)
        {
            if (param.DelIds.Count == 0)
                return Ok(JsonConvert.SerializeObject(new ResultData(ErrorCodeConst.ParameterError)));
            //List<int> ids = JsonConvert.DeserializeObject<List<int>>(param.strEntity);
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var resultCode = _Purchase_OuterNoteDetailService.Del(param.DelIds, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData(resultCode)));
        }
        public class GetEntityByRequestDIdParam
        {
            public int RequestDId { get; set; }
        }
        public IActionResult GetEntityByRequestDId(GetEntityByRequestDIdParam param)
        {
            var relationList = _purchase_OuterRequestNoteRelationService.GetRelationListByRequestIds(new List<int>() { param.RequestDId });
            var Note = _purchase_OuterNoteService.GetPurchase_OuterNoteDetail(relationList[0].OuterNoteId);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = Note }));
        }
        public class GetPayListParam
        {
            public int NoteId { get; set; }
        }
        public IActionResult GetPayList(GetPayListParam param)
        {
            var PayRelationList = _Purchase_OuterNotePayRelationService.GetListByOuterNoteIds(new List<int>() { param.NoteId });
            if(PayRelationList.Count==0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = "" }));
            }
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var Tuple = FinanceServiceHelp.Instance.GetPayListByIds(userToken,PayRelationList.Select(x=>x.PayNoteId).ToList());//
            foreach(var entity in Tuple.list)
            {
                entity.MatchMoney = PayRelationList.Find(x => x.PayNoteId == entity.Id).MatchMoney;
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = Tuple.code, data = Tuple.list }));
        }
        public class SaveNotePayRelationParam
        {
            public int OuterNoteId { get; set; }
            public int PayNoteId { get; set; }
            public decimal MatchMoney { get; set; }
        }
        public IActionResult SaveNotePayRelation(SaveNotePayRelationParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            Purchase_OuterNotePayRelation entity = new Purchase_OuterNotePayRelation();
            entity.Id = 0;
            entity.OuterNoteId = param.OuterNoteId;
            entity.PayNoteId = param.PayNoteId;
            entity.MatchMoney = param.MatchMoney;
            _Purchase_OuterNotePayRelationService.Save(entity, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = entity }));
        }
        public IActionResult UpdateRelationPayAmount(SaveNotePayRelationParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            _Purchase_OuterNotePayRelationService.UpdateRelationMoney(param.OuterNoteId, param.PayNoteId, param.MatchMoney, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }
        public class GetRelationPayListParam
        {
            public int NoteId { get; set; }
        }
        public IActionResult GetRelationPayList(GetRelationPayListParam param)
        {
            //var list = _Purchase_OuterNotePayRelationService.GetListByOuterNoteIds(new List<int>() { param.NoteId});
            var list = _Purchase_OuterNotePayRelationService.GetListAll();
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }
       
        public class SaveRelationPayParam
        {
            public int NoteId { get; set; }
            public List<SaveRelationPayParamPayList> PayList { get; set; }
        }
        public class SaveRelationPayParamPayList
        {
            public int PayId { get; set; }
            public decimal MatchMoney { get; set; }
        }
        public IActionResult SaveRelationPay(SaveRelationPayParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            foreach (var d in param.PayList)
            {
               // _Purchase_OuterNotePayRelationService.UpdateRelationMoney(param.NoteId, d.PayId, d.MatchMoney, userToken);
                Purchase_OuterNotePayRelation entity = new Purchase_OuterNotePayRelation();
                entity.Id = 0;
                entity.OuterNoteId = param.NoteId;
                entity.PayNoteId = d.PayId;
                entity.MatchMoney = d.MatchMoney;
                _Purchase_OuterNotePayRelationService.Save(entity, userToken);
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }

        public class GetRelationInvoiceListParam
        {
            public int NoteId { get; set; }
        }
        public IActionResult GetInvoiceList(GetRelationInvoiceListParam param)
        {
            var InvoiceRelationList = _Purchase_OuterNoteInvoiceRelationService.GetListByOuterNoteIds(new List<int>() { param.NoteId });
            if (InvoiceRelationList.Count == 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = "" }));
            }
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var Tuple = FinanceServiceHelp.Instance.GetInvoiceListByIds(userToken, InvoiceRelationList.Select(x => x.InvoiceId).ToList());//
            foreach (var entity in Tuple.list)
            {
                entity.MatchMoney = InvoiceRelationList.Find(x => x.InvoiceId == entity.Id).MatchMoney;
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = Tuple.code, data = Tuple.list }));
        }
        public IActionResult GetRelationInvoiceList(GetRelationInvoiceListParam param)
        {
            //var list = _Purchase_OuterNoteInvoiceRelationService.GetListByOuterNoteIds(new List<int>() { param.NoteId });
            var list = _Purchase_OuterNoteInvoiceRelationService.GetListAll();
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }
        public class SaveRelationInvoiceParam
        {
            public int NoteId { get; set; }
            public List<SaveRelationInvoiceParamInvoiceList> InvoiceList { get; set; }
        }
        public class SaveRelationInvoiceParamInvoiceList
        {
            public int InvoiceId { get; set; }
            public decimal MatchMoney { get; set; }
        }

        public class SaveNoteInvoiceRelationParam
        {
            public int OuterNoteId { get; set; }
            public int InvoiceId { get; set; }
            public decimal MatchMoney { get; set; }
        }
        public IActionResult SaveNoteInvoiceRelation(SaveNoteInvoiceRelationParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            Purchase_OuterNoteInvoiceRelation entity = new Purchase_OuterNoteInvoiceRelation();
            entity.Id = 0;
            entity.OuterNoteId = param.OuterNoteId;
            entity.InvoiceId = param.InvoiceId;
            entity.MatchMoney = param.MatchMoney;
            _Purchase_OuterNoteInvoiceRelationService.Save(entity, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = entity }));
        }
        public IActionResult UpdateRelationInvoiceAmount(SaveNoteInvoiceRelationParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            _Purchase_OuterNoteInvoiceRelationService.UpdateRelationMoney(param.OuterNoteId, param.InvoiceId, param.MatchMoney, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }
        public IActionResult SaveRelationInvoice(SaveRelationInvoiceParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            foreach (var d in param.InvoiceList)
            {
                // _Purchase_OuterNotePayRelationService.UpdateRelationMoney(param.NoteId, d.PayId, d.MatchMoney, userToken);
                Purchase_OuterNoteInvoiceRelation entity = new Purchase_OuterNoteInvoiceRelation();
                entity.Id = 0;
                entity.OuterNoteId = param.NoteId;
                entity.InvoiceId = d.InvoiceId;
                entity.MatchMoney = d.MatchMoney;
                _Purchase_OuterNoteInvoiceRelationService.Save(entity, userToken);
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }
        public class GetPayNoteListParam
        {
            public int PayId { get; set; }
        }
        public IActionResult GetPayNoteList(GetPayNoteListParam param)
        {
            List<Purchase_OuterNotePayRelation> relationList = _Purchase_OuterNotePayRelationService.GetListByPayId(param.PayId);
            List<Purchase_OuterNote> NoteList = _purchase_OuterNoteService.GetRelationList(relationList.Select(x=>x.OuterNoteId).Distinct().ToList());
            foreach(var entity in NoteList)
            {
                entity.RelationMoney = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.MatchMoney);
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = NoteList }));
        }
        public class GetInvoiceNoteListParam
        {
            public int InvoiceId { get; set; }
        }
        public IActionResult GetInvoiceNoteList(GetInvoiceNoteListParam param)
        {
            List<Purchase_OuterNoteInvoiceRelation> relationList = _Purchase_OuterNoteInvoiceRelationService.GetListByInvoiceIds(new List<int>() { param.InvoiceId });
            List<Purchase_OuterNote> NoteList= _purchase_OuterNoteService.GetRelationList(relationList.Select(x => x.OuterNoteId).Distinct().ToList());
            foreach (var entity in NoteList)
            {
                entity.RelationMoney = relationList.FindAll(x => x.OuterNoteId == entity.Id).Sum(x => x.MatchMoney);
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = NoteList }));
        }
        public class UpdatePlusNumParam
        {
            public int NoteId { get; set; }
            public int NoteDId { get; set; }
            public decimal Amount { get; set; }
        }
        public IActionResult UpdatePlusNum(UpdatePlusNumParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            Purchase_OuterNote Note = _purchase_OuterNoteService.GetPurchase_OuterNoteDetail(param.NoteId);
            Purchase_OuterNoteDetail Detail = _Purchase_OuterNoteDetailService.GetEntity(param.NoteDId);
            if(Detail.PlusNum==param.Amount)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = -1 }));
            }
            else
            {
                Note.PlusAmount = Note.PlusAmount - Detail.PlusNum + param.Amount;
                Note.Price= Note.Price - Detail.PlusNum + param.Amount;
                Detail.PlusNum = param.Amount;

                //
                List<Purchase_OuterRequestNoteRelation> RelationList = _purchase_OuterRequestNoteRelationService.GetRelationListByNoteId(param.NoteDId);
                _purchase_OuterNoteService.SaveNote(userToken.UserId, Note);
                _Purchase_OuterNoteDetailService.Save(Detail, userToken);
                foreach ( var relation in RelationList)
                {
                    relation.ExpectMoney = Math.Round((Detail.PriceNum + Detail.PlusNum) / Detail.TypeNum * relation.OuterNum, 2);
                    _purchase_OuterRequestNoteRelationService.Save(relation, userToken);
                }
               
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = Note }));
            }
            //var list = _Purchase_OuterNoteDetailService.GetListByNoteId(param.NoteId);
        }
    }
}
